package org.lionzhou.chatGG.web.controller;

import lombok.AllArgsConstructor;
import org.apache.tomcat.util.buf.StringUtils;
import org.lionzhou.chatGG.web.client.ChatGptClient;
import org.lionzhou.chatGG.web.client.dto.ChatChoiceItemDto;
import org.lionzhou.chatGG.web.client.dto.ChatDto;
import org.lionzhou.chatGG.web.client.dto.ChatResDto;
import org.lionzhou.chatGG.web.config.GGConfig;
import org.lionzhou.chatGG.web.util.DingDingCallBackDto;
import org.lionzhou.chatGG.web.util.common.DingDingUtils;
import org.lionzhou.chatGG.web.util.enterprise.EnterpriseDingDingUtil;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author ZhouLiangCheng
 * @Date 2023/2/10
 * @Version 1.0
 */
@RestController
@RequestMapping("/chat")
@AllArgsConstructor
public class ChatController {

    ChatGptClient chatGptClient;
    DingDingUtils dingDingUtils;
    EnterpriseDingDingUtil enterpriseDingDingUtil;
    GGConfig ggConfig;

    /**
     * 直接通过api调用访问
     *
     * @param chatDto
     * @return
     */
    @PostMapping("/in")
    public ChatResDto in(@RequestBody ChatDto chatDto) {
        ChatResDto post = chatGptClient.post(chatDto);
        if (ggConfig.getEnableDingDingHookRobot()) {
            // 顺便推送到钉钉群
            dingDingUtils.blindBoxSendMsg(post.getChoices().get(0).getText());
        }
        return post;
    }

    /**
     * 钉钉回调接口
     *
     * @param dingDingCallBackDto
     * @return
     */
    @RequestMapping(value = "/dingding", method = {RequestMethod.GET, RequestMethod.POST})
    public String dingding(@RequestBody DingDingCallBackDto dingDingCallBackDto) {
        String text = dingDingCallBackDto.getText().getContent().trim();
        ChatDto chatDto = new ChatDto();
        chatDto.setPrompt(text);
        ChatResDto chatResDto = chatGptClient.post(chatDto);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chatResDto.getChoices().size(); i++) {
            ChatChoiceItemDto itemDto = chatResDto.getChoices().get(i);
            sb.append(itemDto.getText()).append("\n");
        }

        enterpriseDingDingUtil.post(sb.toString(), dingDingCallBackDto.getConversationId());
        return "ok";
    }
}
